package hxy.dragon.secure

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ClipboardManager
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
import org.jetbrains.compose.ui.tooling.preview.Preview

@Composable
@Preview
fun EncryptionApp() {
    MaterialTheme {
        var inputText by remember { mutableStateOf(TextFieldValue("")) }
        var publicKey by remember { mutableStateOf(TextFieldValue("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPSEOTVqftlcxz24oP8erbsq/XqF9cOSjJu9zH4BCJjC aohanhongzhi@qq.com")) }
        var encryptedText by remember { mutableStateOf("") }
        var ciphertext by remember { mutableStateOf(TextFieldValue("")) }
        var privateKey by remember {
            mutableStateOf(
                TextFieldValue(
                    """"""
                )
            )
        }
        var decryptedText by remember { mutableStateOf("") }

        // 获取剪贴板管理器
        val clipboardManager: ClipboardManager = LocalClipboardManager.current

        // 创建Snackbar状态
        val snackbarHostState = remember { SnackbarHostState() }
        val scope = rememberCoroutineScope()

        // 创建加密服务实例
        val cryptoService = CryptoService()

        Scaffold {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp)
                    .verticalScroll(rememberScrollState()),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Top
            ) {
                SnackbarHost(hostState = snackbarHostState)

                Text(
                    "Text Encryption/Decryption App",
                    style = MaterialTheme.typography.headlineMedium
                )

                Spacer(modifier = Modifier.height(16.dp))

                Text("Encryption Section", style = MaterialTheme.typography.titleLarge)

                OutlinedTextField(
                    value = inputText,
                    onValueChange = { inputText = it },
                    label = { Text("Enter plain text") },
                    modifier = Modifier.fillMaxWidth()
                )

                Spacer(modifier = Modifier.height(8.dp))

                OutlinedTextField(
                    value = publicKey,
                    onValueChange = { publicKey = it },
                    label = { Text("Enter recipient's public key (Base64)") },
                    modifier = Modifier.fillMaxWidth()
                )

                Spacer(modifier = Modifier.height(8.dp))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Button(onClick = {
                        // 执行加密逻辑
                        try {
                            if (inputText.text.isNotEmpty() && publicKey.text.isNotEmpty()) {
                                encryptedText =
                                    encryptMessage(inputText.text, publicKey.text, cryptoService)
                            } else {
                                encryptedText = "Please enter both text and public key"
                            }
                        } catch (e: Exception) {
                            encryptedText = "Encryption error: ${e.message}"
                        }
                    }) {
                        Text("Encrypt")
                    }

                    Button(onClick = {
                        // 自测：对称加解密回归
                        try {
                            val testText = "测试123 Test"
                            val testKey = ByteArray(32) { it.toByte() }
                            val encrypted = cryptoService.encrypt(testText, testKey)
                            val decrypted = cryptoService.decrypt(encrypted, testKey)
                            encryptedText =
                                "对称自测: 原文='$testText' 解密='$decrypted' ${if (testText == decrypted) "✓" else "✗不一致"}"
                        } catch (e: Exception) {
                            encryptedText = "对称自测失败: ${e.message}"
                        }
                    }) {
                        Text("对称自测")
                    }

                    Button(onClick = {
                        // 端到端自测：用当前输入的公私钥进行完整加解密
                        try {
                            val testMsg = "1"
                            val encrypted = encryptMessage(testMsg, publicKey.text, cryptoService)
                            val decrypted =
                                decryptMessage(encrypted, privateKey.text, cryptoService)
                            encryptedText =
                                "端到端: 原文='$testMsg' 解密='$decrypted' ${if (testMsg == decrypted) "✓" else "✗不一致! 密文=$encrypted"}"
                        } catch (e: Exception) {
                            encryptedText =
                                "端到端自测失败: ${e.message}\n${e.stackTraceToString().take(200)}"
                        }
                    }) {
                        Text("端到端自测")
                    }
                }

                Spacer(modifier = Modifier.height(8.dp))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text("Encrypted Text: $encryptedText", modifier = Modifier.weight(1f))
                    Button(onClick = {
                        clipboardManager.setText(AnnotatedString(encryptedText))
                        scope.launch {
                            snackbarHostState.showSnackbar("Encrypted text copied to clipboard")
                        }
                    }) {
                        Text("Copy")
                    }
                }

                Spacer(modifier = Modifier.height(32.dp))

                Text("Decryption Section", style = MaterialTheme.typography.titleLarge)

                OutlinedTextField(
                    value = ciphertext,
                    onValueChange = { ciphertext = it },
                    label = { Text("Enter ciphertext") },
                    modifier = Modifier.fillMaxWidth()
                )

                Spacer(modifier = Modifier.height(8.dp))

                OutlinedTextField(
                    value = privateKey,
                    onValueChange = { privateKey = it },
                    label = { Text("Enter your private key (Base64)") },
                    modifier = Modifier.fillMaxWidth()
                )

                Spacer(modifier = Modifier.height(8.dp))

                Button(onClick = {
                    // 执行解密逻辑
                    try {
                        if (ciphertext.text.isNotEmpty() && privateKey.text.isNotEmpty()) {
                            decryptedText =
                                decryptMessage(ciphertext.text, privateKey.text, cryptoService)
                        } else {
                            decryptedText = "Please enter both ciphertext and private key"
                        }
                    } catch (e: Exception) {
                        decryptedText = "Decryption error: ${e.message}"
                    }
                }) {
                    Text("Decrypt")
                }

                Spacer(modifier = Modifier.height(8.dp))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text("Decrypted Text: $decryptedText", modifier = Modifier.weight(1f))
                    Button(onClick = {
                        clipboardManager.setText(AnnotatedString(decryptedText))
                        scope.launch {
                            snackbarHostState.showSnackbar("Decrypted text copied to clipboard")
                        }
                    }) {
                        Text("Copy")
                    }
                }
            }
        }
    }

}